package com.uphone.edwards.pro.activity.login.register;


import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.annotation.RequiresApi;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.Gson;
import com.radish.baselibrary.Intent.IntentUtils;
import com.radish.baselibrary.utils.LogUtils;
import com.radish.baselibrary.utils.ToastUtil;
import com.uphone.edwards.MainActivity;
import com.uphone.edwards.MyApp;
import com.uphone.edwards.R;
import com.uphone.edwards.adapter.AddressAdapter;
import com.uphone.edwards.adapter.LanguageAdapter;
import com.uphone.edwards.base.mvp.BaseMvpActivity;
import com.uphone.edwards.modle.AddressBean;
import com.uphone.edwards.pro.activity.login.LoginActivity;
import com.uphone.edwards.util.LanguageType;
import com.uphone.edwards.util.LanguageUtils;
import com.uphone.edwards.util.SharedUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by hzy on 2019/12/23
 * LoginContract
 *
 * @author Administrator
 */
public class RegisterActivity extends BaseMvpActivity<RegisterPresenter> implements RegisterContract.View {
    @BindView(R.id.tv_register)
    TextView tvRegister;
    @BindView(R.id.tv_register_language)
    TextView tvRegisterLanguage;
    @BindView(R.id.tv_send_code)
    TextView tvSendCode;
    @BindView(R.id.tv_address_select)
    TextView tvAddressSelect;
    @BindView(R.id.lv_address)
    ListView lvAddress;
    @BindView(R.id.et_username)
    EditText etUsername;
    @BindView(R.id.et_gonghao)
    EditText etGonghao;
    @BindView(R.id.et_bumen)
    EditText etBumen;
    @BindView(R.id.et_zhicheng)
    EditText etZhicheng;
    @BindView(R.id.et_email)
    EditText etEmail;
    @BindView(R.id.et_code)
    EditText etCode;
    @BindView(R.id.lv_lang)
    ListView lvLang;
    @BindView(R.id.rl_gone)
    RelativeLayout rlGone;
    private MyCountDownTimer timer;

    private static final long TIME = 60 * 1000L;
    private static final long INTERVAL = 1000L;

    private AddressAdapter aAdapter;
    private boolean addressFlag;
    private RegisterPresenter mPresenter;

    //true 代表隐藏状态，false代表显示状态    语言选择弹框
    private boolean langFlag;

    private LanguageAdapter langAdapter;

    @Override
    protected void initInject() {

    }

    @Override
    protected void initBundle() {

    }

    @Override
    protected int initLayout() {
        return R.layout.activity_register;
    }

    @Override
    protected void initView() {
        mPresenter = new RegisterPresenter();
        mPresenter.attachView(this);
        mPresenter.postAddress();
        //判断设置对应语言
        if (LanguageType.ENGLISH.getLanguage().equals(SharedUtils.getShareLanguage(this))) {
            tvRegisterLanguage.setText(getResources().getString(R.string.yingyu));
        }
        if (LanguageType.CHINESE.getLanguage().equals(SharedUtils.getShareLanguage(this))) {
            tvRegisterLanguage.setText(getResources().getString(R.string.zhongwen));
        }
        if (LanguageType.KOREA.getLanguage().equals(SharedUtils.getShareLanguage(this))) {
            tvRegisterLanguage.setText(getResources().getString(R.string.hanwen));
        }
        if (LanguageType.JAPAN.getLanguage().equals(SharedUtils.getShareLanguage(this))) {
            tvRegisterLanguage.setText(getResources().getString(R.string.riwen));
        }

        //地区选择列表
        aAdapter = new AddressAdapter(this);
        lvAddress.setAdapter(aAdapter);

        langAdapter = new LanguageAdapter(this);
        List<Integer> listInt = new ArrayList<>();
        listInt.add(R.string.zhongwen);
        listInt.add(R.string.yingyu);
        listInt.add(R.string.riwen);
        listInt.add(R.string.hanwen);
        lvLang.setAdapter(langAdapter);
        langAdapter.setData(listInt);
    }

    @Override
    protected void initTitle() {

    }

    @Override
    protected void initData() {

    }

    @Override
    protected void initListener() {
        lvAddress.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                tvAddressSelect.setText(aAdapter.getItem(i));
                lvAddress.setVisibility(View.GONE);
                addressFlag = false;
            }
        });


        //语言选择
        lvLang.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                String language = null;
                switch (i) {
                    case 0:
                        //切换为简体中文
                        language = LanguageType.CHINESE.getLanguage();
                        tvRegisterLanguage.setText(getResources().getString(R.string.zhongwen));
                        break;
                    case 1:
                        //切换为英语
                        language = LanguageType.ENGLISH.getLanguage();
                        tvRegisterLanguage.setText(getResources().getString(R.string.yingyu));
                        break;
                    case 2:
                        //切换为日语
                        language = LanguageType.JAPAN.getLanguage();
                        tvRegisterLanguage.setText(getResources().getString(R.string.riwen));
                        break;
                    case 3:
                        //切换为韩语
                        language = LanguageType.KOREA.getLanguage();
                        tvRegisterLanguage.setText(getResources().getString(R.string.hanwen));
                        break;
                    default:
                        break;
                }
                changeLanguage(language);
            }
        });
    }

    /**
     * 如果是7.0以下，我们需要调用changeAppLanguage方法，
     * 如果是7.0及以上系统，直接把我们想要切换的语言类型保存在SharedPreferences中,然后重新启动MainActivity即可
     *
     * @param language
     */
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    private void changeLanguage(String language) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
            LanguageUtils.changeAppLanguage(RegisterActivity.this, language);
        }
        SharedUtils.putShareLanguage(language, RegisterActivity.this);
        if ("en".equals(language)){
            MyApp.languageType = "2";
        }
        if ("ch".equals(language)){
            MyApp.languageType = "1";
        }
        if ("ja".equals(language)){
            MyApp.languageType = "3";
        }
        if ("ko".equals(language)){
            MyApp.languageType = "4";
        }
        Intent intent = new Intent(this, RegisterActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
        finish();
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick({R.id.tv_register, R.id.tv_send_code, R.id.tv_address_select, R.id.tv_register_language})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_register:
                String address = tvAddressSelect.getText().toString();
                String email = etEmail.getText().toString();
                String gonghao = etGonghao.getText().toString();
                String bumen = etBumen.getText().toString();
                String zhicheng = etZhicheng.getText().toString();
                String code = etCode.getText().toString();
                if ("".equals(address)){
                    ToastUtils.showShort("请选择您所在的国家");
                    return;
                }
                String name = etUsername.getText().toString();
                if ("".equals(name)) {
                    ToastUtils.showShort("请输入名字");
                    return;
                }
                if ("".equals(email)) {
                    ToastUtils.showShort("请输入邮箱");
                    return;
                }
                if ("".equals(gonghao)) {
                    ToastUtils.showShort("请输入工号");
                    return;
                }
                if ("".equals(bumen)) {
                    ToastUtils.showShort("请输入部门");
                    return;
                }
                if ("".equals(zhicheng)) {
                    ToastUtils.showShort("请输入职称");
                    return;
                }
                if ("".equals(code)) {
                    ToastUtils.showShort("请输入验证码");
                    return;
                }
                mPresenter.postRegist(address , name , bumen , gonghao , "245851597@qq.com" , zhicheng , code);
                break;
            case R.id.tv_send_code:
                String userName = etUsername.getText().toString();
                if ("".equals(userName)) {
                    ToastUtils.showShort("请输入名字");
                    return;
                }
                if ("".equals(etEmail.getText().toString())) {
                    ToastUtils.showShort("请输入邮箱");
                    return;
                }
                mPresenter.postRegistCode();
                break;
            case R.id.tv_address_select:
                if (addressFlag) {
                    addressFlag = false;
                    lvAddress.setVisibility(View.GONE);
                } else {
                    addressFlag = true;
                    lvAddress.setVisibility(View.VISIBLE);
                }
                break;
            case R.id.tv_register_language:
                if (langFlag == false) {
                    rlGone.setVisibility(View.VISIBLE);
                    langFlag = true;
                } else {
                    rlGone.setVisibility(View.GONE);
                    langFlag = false;
                }
                break;
        }
    }

    @Override
    public void addressView(String responseBean, int status) {
        Gson gson = new Gson();
        AddressBean bean = gson.fromJson(responseBean, AddressBean.class);
        if (0 == bean.getCode()) {
            aAdapter.setData(bean.getLocations());
        }
    }

    @Override
    public void registView(String responseBean, int status) {
        LogUtils.e(responseBean);
        try {
            JSONObject jsonObject = new JSONObject(responseBean);
            ToastUtils.showShort(jsonObject.getString("msg"));
            if (0 == jsonObject.getInt("code")){
                IntentUtils.getInstance()
                    .with(this, MainActivity.class)
                    .start();
                finish();
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }
    //获取验证码
    @Override
    public void registCodeView(String responseBean, int status) {
        try {
            JSONObject jsonObject = new JSONObject(responseBean);
            if (0 == jsonObject.getInt("code")){
                startTimer();
            }
            ToastUtils.showShort(jsonObject.getString("msg"));
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }


    /**
     * 开始倒计时
     */
    private void startTimer() {
        tvSendCode.setClickable(false);//不让这个控件点击
        if (timer == null) {
            timer = new MyCountDownTimer(TIME, INTERVAL);
        }
        timer.start();
    }

    /**
     * 取消倒计时
     */
    private void cancelTimer() {
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        cancelTimer();
    }


    class MyCountDownTimer extends CountDownTimer {
        public MyCountDownTimer(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            long time = millisUntilFinished / 1000;
            tvSendCode.setTextColor(0xFF3CC8C8);
            if (time <= 59) {
                tvSendCode.setText(String.format("%02d s", time));
            } else {
                tvSendCode.setText(String.format("%02d:%02d", time / 60, time % 60));
            }
        }

        @Override
        public void onFinish() {
            tvSendCode.setText(getResources().getString(R.string.fasongyanzhengma));
            tvSendCode.setTextColor(0xFF3CC8C8);
            cancelTimer();
            tvSendCode.setClickable(true);//让这个控件能点击
        }

    }

}
